package com.lonty.intelligence.util;

import com.alibaba.fastjson.JSONException;
import com.github.qcloudsms.SmsMultiSender;
import com.github.qcloudsms.SmsMultiSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;

import java.io.IOException;

/**
 * @Author 陈璇
 * @Date 2020/4/14 17:37
 * @Version 1.0
 **/
public class SendMessageUtils {

    private static int app_id = 1400323855;
    private static String app_key = "51022153df7bcbb89059ba083da32fcd";
    private static String sign = "天诚online";

    /**
     * 发送信息
     *
     * @author lingting 2019-06-12 15:09:37
     */
    public static SmsMultiSenderResult send(String phone, int templateId, String[] params) {
        return send(new String[]{phone}, templateId, params);
    }

    /**
     * 同时发送多个手机号信息
     *
     * @author lingting 2019-06-12 15:10:11
     */
    public static SmsMultiSenderResult send(String[] phones, int templateId, String[] params) {
        // 创建发送器
        SmsMultiSender sender = new SmsMultiSender(app_id, app_key);
        // 初始化结果
        SmsMultiSenderResult senderResult = new SmsMultiSenderResult();

        // 初始失败结果
        senderResult.result = -1;
        Exception exception = null;

        try {
            // 发送短信并覆盖初识结果
            senderResult = sender.sendWithParam(
                    "86",
                    phones,
                    templateId,
                    params,
                    sign,
                    "",
                    ""
            );

        } catch (HTTPException e) {
            senderResult.errMsg = "网络异常!";
            exception = e;
        } catch (IOException e) {
            senderResult.errMsg = "IO流异常!";
            exception = e;
        } catch (JSONException e) {
            senderResult.errMsg = "JSON解析异常!";
            exception = e;
        }

        // 记录发送失败日志
        if (senderResult.result != 0) {
            if (exception != null) {
                System.out.println("短信发送失败: " + senderResult.errMsg);
                System.out.println("短信发送失败: " + senderResult.result);
                System.out.println("短信发送失败: " + senderResult.details);
                System.out.println("短信发送失败: " + senderResult.ext);
            } else {
                System.out.println("短信发送失败: " + senderResult.errMsg);
                System.out.println("短信发送失败: " + senderResult.result);
                System.out.println("短信发送失败: " + senderResult.details);
                System.out.println("短信发送失败: " + senderResult.ext);
            }
        }

        return senderResult;
    }

}
